﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mvvm;
using System.Collections.ObjectModel;
using System.IO;
using System.Diagnostics;

namespace CodeIn.Modules.Ui.FileExplorer {
	public class FileExplorerViewModel : BaseViewModel {
		public ObservableCollection<FileExplorerItemViewModel> Roots { get; private set; }

		public FileExplorerViewModel() {
			Roots = new ObservableCollection<FileExplorerItemViewModel>();

			var drives = DriveInfo.GetDrives();
			foreach (var drive in drives) {
				Roots.Add(FileExplorerItemViewModel.FromDrive(drive));
			}
		}

		public void NavigateToPath(string fullPath) {
			DirectoryInfo info = new DirectoryInfo(fullPath);
			if (info.Exists) {
				var item = Roots.First(root => root.Name == info.Root.Name);
				item.IsExpanded = true;

				string path = info.FullName.Remove(0, info.Root.Name.Length);
				var parts = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);

				for (int i = 0; i < parts.Length; i++) {
					item = item.Children.First(it => it.Name == parts[i]);
					item.IsExpanded = true;
				}

				item.IsSelected = true;
			}
		}
	}
}
